<template>
  <div>
    <div class="btn" style="padding-bottom: 16px">
      <el-button type="primary" size="small" @click="changeSaveTree"
        >保存</el-button
      >
      <el-button type="primary" size="small">取消</el-button>
    </div>
    <div class="antv-content">
      <div class="tree">
        <el-tree
          :data="datas"
          show-checkbox
          node-key="capacityId"
          ref="tree"
          highlight-current
          :props="defaultProps"
          @check="changeNodes"
        >
        </el-tree>
      </div>
      <div id="g-container">
        <div id="container"></div>
      </div>
    </div>
  </div>
</template>
<script>
import { getresolveTree, retention, queryCapability } from "@/api/project";
import G6 from "@antv/g6";
import insertCss from "insert-css";
// 我们用 insert-css 演示引入自定义样式
// 推荐将样式添加到自己的样式文件中
// 若拷贝官方代码，别忘了 npm install insert-css
insertCss(`
  .g6-tooltip {
    border-radius: 6px;
    font-size: 12px;
    color: #fff;
    background-color: #000;
    padding: 2px 8px;
    text-align: center;
  }
`);
export default {
  data() {
    return {
      data: {
        nodes: [],
        edges: [],
      },
      graph: null,
      list: [],
      datas: [],
      defaultProps: {
        children: "childCapacities",
        label: "capacityName",
      },
    };
  },
  mounted() {
    this.getdata();
  },
  methods: {
    getdata() {
      getresolveTree()
        .then((res) => {
          const { code, data } = res?.data;
          if (code == 200) {
            this.datas = data;
            queryCapability({ taskId: localStorage.getItem("taskId") })
              .then((res) => {
                const data = res.data.data;
                data.forEach((item, index) => {
                  if (item.length == 1) {
                    data.splice(index, 1);
                  }
                });
                this.$refs.tree.setCheckedKeys(data);
                this.changeNodes();
              })
              .catch((err) => {
                console.log(err);
              });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    changeNodes() {
      this.list = [];
      const a = this.$refs.tree.getCheckedKeys();
      const b = this.$refs.tree.getHalfCheckedKeys();

      const z = this.$refs.tree.getCheckedNodes();
      const x = this.$refs.tree.getHalfCheckedNodes();
      const v = JSON.parse(JSON.stringify(z.concat(x)));
      v.forEach((item) => {
        item.id = item.capacityId;
        if (item.childCapacities) {
          delete item.childCapacities;
        }
      });
      this.data.nodes = v;
      const c = this.walkTreeData(this.datas, a.concat(b));
      this.treeFlat(c);
      this.data.edges = this.list;
      this.getGraph();
    },

    treeFlat(q, w) {
      q.forEach((item) => {
        if (w) {
          this.list.push({
            source: w,
            target: item.capacityId,
          });
        }
        if (item.childCapacities && item.childCapacities.length) {
          this.treeFlat(item.childCapacities, item.capacityId);
        }
      });
    },

    walkTreeData(datas, selectedKeys) {
      const ret = [];
      datas.forEach((node) => {
        const newNode = { ...node };
        delete newNode.childCapacities;
        node.childCapacities &&
          (newNode.childCapacities = this.walkTreeData(
            node.childCapacities,
            selectedKeys
          ));
        if (
          selectedKeys.includes(newNode.capacityId) ||
          (newNode.childCapacities && newNode.childCapacities.length)
        ) {
          ret.push(newNode);
        }
      });
      return ret;
    },
    getGraph() {
      G6.registerNode(
        "sql",
        {
          drawShape(cfg, group) {
            const rect = group.addShape("rect", {
              attrs: {
                x: -75,
                y: -25,
                width: 150,
                height: 50,
                radius: 10,
                stroke: "#07f",
                fill: "#fff",
                lineWidth: 1,
              },
              name: "rect-shape",
            });
            if (cfg.capacityName) {
              group.addShape("text", {
                attrs: {
                  text: cfg.capacityName,
                  x: 0,
                  y: 0,
                  fill: "#000",
                  fontSize: 14,
                  textAlign: "center",
                  textBaseline: "middle",
                  fontWeight: "500",
                },
                name: "text-shape",
              });
            }
            return rect;
          },
        },
        "single-node"
      );
      const g = document.getElementById("g-container");
      const container = document.getElementById("container");
      const width = g.clientWidth;
      const height = g.clientHeight;
      if (this.graph) {
        this.graph.destroy();
      }
      this.graph = new G6.Graph({
        container: "container",
        width,
        height,
        layout: {
          type: "dagre",
          nodesepFunc: (d) => {
            if (d.id === "3") {
              return 500;
            }
            return 50;
          },
          ranksep: 70,
          controlPoints: true,
        },
        defaultNode: {
          type: "sql",
        },
        defaultEdge: {
          type: "polyline",
          style: {
            radius: 20,
            offset: 45,
            endArrow: true,
            lineWidth: 2,
            stroke: "#C2C8D5",
          },
        },
        nodeStateStyles: {
          selected: {
            stroke: "#d9d9d9",
            fill: "#5394ef",
          },
        },
        modes: {
          default: [
            "drag-canvas",
            "zoom-canvas",
            "click-select",
            // {
            //   type: "tooltip",
            //   formatText(model) {
            //     const cfg = model.conf;
            //     const text = [];
            //     cfg.forEach((row) => {
            //       text.push(row.label + ":" + row.value + "<br>");
            //     });
            //     return text.join("\n");
            //   },
            //   offset: 30,
            // },
          ],
        },
        fitView: true,
        minZoom: 0.001,
      });
      this.graph.data(this.data);
      this.graph.render();
      if (typeof window !== "undefined")
        window.onresize = () => {
          if (!this.graph || this.graph.get("destroyed")) return;
          if (!container || !g.clientWidth || !g.clientHeight) return;
          this.graph.changeSize(g.clientWidth, g.clientHeight);
        };
    },
    changeSaveTree() {
      const list = this.$refs.tree.getCheckedKeys();
      const x = this.$refs.tree.getHalfCheckedKeys();
      const id = localStorage.getItem("taskId");
      retention({
        taskId: id,
        ids: list.concat(x),
      }).then((res) => {
        console.log(res);
        this.getdata();
      });
    },
  },
};
</script>
<style>
#g-container {
  width: calc(100% - 400px);
  height: calc(100vh - 287px);
}
.tree {
  width: 400px;
  height: calc(100vh - 287px);
}
.antv-content {
  display: flex;
  justify-content: space-between;
  height: calc(100vh - 287px);
  overflow: auto;
}
</style>
